﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using System.Web.Security;

namespace SSOExample
{
    public partial class SignInWithWordpress : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            OpenIdRelyingParty openIdRelyingParty = new OpenIdRelyingParty();
            var response = openIdRelyingParty.GetResponse();
            if (response != null)
            {
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        // This is where you would look for any OpenID extension responses included
                        // in the authentication assertion.
                        var claimsResponse = response.GetExtension<ClaimsResponse>();

                        // Store off the "friendly" username to display -- NOT for username lookup
                        string FriendlyLoginName = response.FriendlyIdentifierForDisplay;

                        // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
                        // with the OpenID Claimed Identifier as their username.
                        FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
                        base.Response.Redirect(FormsAuthentication.DefaultUrl);
                        break;
                    case AuthenticationStatus.Failed:
                        break;
                    case AuthenticationStatus.Canceled:
                        break;
                }
            }

            IAuthenticationRequest request = openIdRelyingParty.CreateRequest("username.wordpress.com");
            // This is where you would add any OpenID extensions you wanted
            // to include in the authentication request.
            request.AddExtension(new ClaimsRequest
            {
                Country = DemandLevel.Request,
                Email = DemandLevel.Request,
                Gender = DemandLevel.Require,
                PostalCode = DemandLevel.Require,
                TimeZone = DemandLevel.Require,
            });
            request.RedirectToProvider();
        }
    }
}
